﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using CommDll;
using DevComponents.DotNetBar;
using System.Drawing.Imaging;

namespace HospitalMedicineTraceability
{
    public partial class frmCollectPharmacyStockOut : DevComponents.DotNetBar.OfficeForm
    {
        public Dictionary<string, string> m_dictInfo = new Dictionary<string, string>();
        public DataTable m_dt = new DataTable();
        public Boolean m_bIsRefresh = false;    //是否刷新数据
        public string m_strBillCode = "";
        public string m_strSupervisionCode = ""; 
        // 扫码信息
        private Dictionary<string, PanelEx> m_dictPnl = new Dictionary<string, PanelEx>();
        private Dictionary<string, LabelX> m_dictGoodsName = new Dictionary<string, LabelX>();
        private Dictionary<string, LabelX> m_dictGoodsSpec = new Dictionary<string, LabelX>();
        private Dictionary<string, TextBox> m_dictAmount = new Dictionary<string, TextBox>();
        private Dictionary<string, TextBox> m_dictCollectAmount = new Dictionary<string, TextBox>();
        private Dictionary<string, TextBox> m_dictCollectCount = new Dictionary<string, TextBox>();
        private Dictionary<string, TextBox> m_dictCollectStatus  = new Dictionary<string, TextBox>();
        public frmCollectPharmacyStockOut()
        {
            InitializeComponent();
            timerShowData.Enabled = false;            
        }

        #region 01 自定义方法
 
        /// <summary>
        /// 取单据汇总数据
        /// </summary>
        private void _getBillTotal()
        {
            int nGoodsCount = 0; // 商品品种数
            int nGoodsCount1 = 0; // 已复核商品品种数
            int nGoodsCount0 = 0; // 未复核商品品种数
            double dGoodsCollectAmount = 0; // 已采数
            try
            {
                nGoodsCount = (m_dt == null)?0: m_dt.Rows.Count;                
                for (int i = 0; i < nGoodsCount; i++)
                {
                    if (m_dt.Rows[i]["SupervisionCodeCollectStatus"].ToString().Equals("全采"))
                    {
                        nGoodsCount1 += 1;
                    }
                    dGoodsCollectAmount += FunctionComm._strToFloat(m_dt.Rows[i]["SupervisionCodeCollectAmount"].ToString());
                }
                
                nGoodsCount0 = nGoodsCount - nGoodsCount1;
                txtGoodsCount0.Text = nGoodsCount0.ToString();
                txtGoodsCount1.Text = nGoodsCount1.ToString();
                lblBillCheckStatus.Text = "未采";
                lblBillCheckStatus.Text = nGoodsCount1 > 0 ? "部采" : lblBillCheckStatus.Text;
                lblBillCheckStatus.Text = (nGoodsCount1 > 0 && nGoodsCount1 == nGoodsCount) ? "全采" : lblBillCheckStatus.Text;
                lblBillCheckStatus.Text = (dGoodsCollectAmount == 0) ? "未采" : lblBillCheckStatus.Text;
                txtGoodsCount.Text = nGoodsCount.ToString();
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            }            
            if (nGoodsCount1 > 0 && nGoodsCount0 == nGoodsCount)
            {
                btnNext_Click(null, null);
            }
        }

        /// <summary>
        /// 取单据信息
        /// </summary>
        private void _getBillList()
        {
            string strSql = "";
            try
            {
                strSql = @"select Id,StockOut_Code as BillCode,DetailCode as BillDetailCode,Code,Name,PackageSpec,Manufacturer
,Amount = Convert(float,Amount)
,SupervisionCodeCollectAmount = Convert(float,SupervisionCodeCollectAmount)
,SupervisionCodeCollectCount
,SupervisionCodeCollectStatus = case when isnull(SupervisionCodeCollectStatus,'') = '' then '未采' else SupervisionCodeCollectStatus end"
                        + " from TH_PharmacyStockOutDetail where StockOut_Code = '{0}'";                        
                strSql = string.Format(strSql,m_strBillCode);
                m_dt = AppInfo._openSql_DataTable(strSql);                
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
            }
            // 显示商品信息
            for (int i = 1; i <= 10; i++)
            {
                if (m_dt != null && m_dt.Rows.Count > 0 && i <= m_dt.Rows.Count)
                {
                    m_dictPnl[i.ToString()].Visible = true;
                    m_dictGoodsName[i.ToString()].Visible = true;
                    m_dictGoodsSpec[i.ToString()].Visible = true;
                    m_dictAmount[i.ToString()].Visible = true;
                    m_dictCollectAmount[i.ToString()].Visible = true;
                    m_dictCollectCount[i.ToString()].Visible = true;
                    m_dictCollectStatus[i.ToString()].Visible = true;

                    m_dictGoodsName[i.ToString()].Text = string.Format("({0}){1}", m_dt.Rows[i - 1]["Code"].ToString(),m_dt.Rows[i - 1]["Name"].ToString());
                    m_dictGoodsSpec[i.ToString()].Text = m_dt.Rows[i - 1]["PackageSpec"].ToString();
                    m_dictAmount[i.ToString()].Text = m_dt.Rows[i - 1]["Amount"].ToString();
                    m_dictCollectAmount[i.ToString()].Text = m_dt.Rows[i - 1]["SupervisionCodeCollectAmount"].ToString();
                    m_dictCollectCount[i.ToString()].Text = m_dt.Rows[i - 1]["SupervisionCodeCollectCount"].ToString();
                    m_dictCollectCount[i.ToString()].BackColor = Color.Black;
                    m_dictCollectStatus[i.ToString()].Text = m_dt.Rows[i - 1]["SupervisionCodeCollectStatus"].ToString();
                    m_dictCollectStatus[i.ToString()].BackColor = m_dictCollectStatus[i.ToString()].Text.Equals("全采") ? Color.Red : Color.Black;
                }
                else {
                    m_dictPnl[i.ToString()].Visible = false;
                }
            }
            // 汇总数据
            _getBillTotal();
        }

         /// <summary>
        /// 保存扫码信息
        /// </summary>
        /// <param name="strCode"></param>
        /// <param name="bIsNew"></param>
        private Boolean _saveCode()
        {
            Boolean bResult = false;
            try
            {
                // 保存数据
                string strSql = string.Format("exec P_DealPharmacyStockOut 'Collect_SaveSupervisionCode','{0}@{1}@{2}@{3}'", m_strBillCode, m_strSupervisionCode
                , AppInfo.m_UserInfo.m_strCode, AppInfo.m_UserInfo.m_strName);
                DataTable dt = AppInfo._openSql_DataTable(strSql);
                string strResultKind = dt.Rows[0]["Result"].ToString();
                bResult = strResultKind.Equals("1");
                if (!bResult)
                {
                    CommFun._messageBoxShow(dt.Rows[0]["Message"].ToString());
                }
                else
                {
                    // 数量加本次数量
                    m_bIsRefresh = true;
                    bResult = true;
                }
            }
            catch {
                bResult = false;
            }
            return bResult;
        }

        /// <summary>
        /// 处理编码
        /// </summary>
        private void _dealCode()
        {
            try
            {
                //电监码核对
                string strSql = "";
                strSql = string.Format("exec P_DealPharmacyStockOut 'Collect_CheckSupervisionCode','{0}@{1}'", m_strBillCode,m_strSupervisionCode);
                DataTable dt = AppInfo._openSql_DataTable(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    string strResult = dt.Rows[0]["Result"].ToString();
                    // 未核对成功
                    if (strResult == "0")
                    {
                        lblHint.Text = string.Format("校对提示：{0}", dt.Rows[0]["Message"].ToString());
                    }
                    else if (strResult == "2")
                    {
                        if (CommFun._messageBoxShow("该电监码未对码，是否现在对码？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                        {
                            frmGoodsCodeCheck frm = new frmGoodsCodeCheck();
                            frm.m_dictInfo.Add("Code", m_strSupervisionCode);
                            frm.m_dictInfo.Add("Name", dt.Rows[0]["Name"].ToString());
                            frm.m_dictInfo.Add("PackageSpec", dt.Rows[0]["PackageSpec"].ToString());
                            frm.m_dictInfo.Add("Unit", dt.Rows[0]["Unit"].ToString());
                            frm.m_dictInfo.Add("Manufacturer", dt.Rows[0]["Manufacturer"].ToString());
                            if (frm.ShowDialog() != DialogResult.OK)
                            {
                                return;
                            }
                            else {
                                _dealCode();
                                return;
                            }
                        }
                    }
                    else
                    {
                        lblHint.Text = string.Format("校对提示：{0}", "采集正常");
                        // 显示商品信息
                        txtCode.Text = dt.Rows[0]["Code"].ToString();
                        txtSupervisionCode0.Text = dt.Rows[0]["SupervisionCode"].ToString();
                        txtName.Text = dt.Rows[0]["Name"].ToString();
                        txtPackageSpec.Text = dt.Rows[0]["PackageSpec"].ToString();
                        txtUnit.Text = dt.Rows[0]["Unit"].ToString();
                        txtForm.Text = dt.Rows[0]["Form"].ToString();
                        txtManufacturer.Text = dt.Rows[0]["Manufacturer"].ToString();
                        txtMakeDate.Text = dt.Rows[0]["MakeDate"].ToString();
                        txtExpiredDate.Text = dt.Rows[0]["ExpiredDate"].ToString();
                        txtPackageName.Text = dt.Rows[0]["PackageName"].ToString();
                        txtPackageRatio.Text = dt.Rows[0]["PackageRatio"].ToString();
                        // 保存数据
                        if (_saveCode()) {
                            // 更新数据
                            _getBillList();
                        };
                        return;
                    }
                }
            }
            catch { }
        }
       
        #endregion

        #region  02 窗体相关事件方法
        private void frmConfig_Load(object sender, EventArgs e)
        {
            // 新单据
            this.DoubleBuffered = true;
            pnlNext.Top = (this.Height - pnlNext.Height) / 2 - 20;
            pnlNext.Left = (this.Width - pnlNext.Width) / 2;
            if (!m_dictInfo.ContainsKey("BillCode"))
            {
                m_dictInfo.Add("BillCode", "");
            }
            gbScan.Text = string.Format("药品明细信息({0})",0);           
            // 初始化控件
            foreach (Control ctrl in gbScan.Controls)
            {
                if (ctrl.Name.Contains("pnl"))
                {
                    m_dictPnl.Add(ctrl.Name.Replace("pnl", ""), (PanelEx)ctrl);
                    foreach (Control ctrl1 in ctrl.Controls)
                    {
                        try
                        {
                            if (ctrl1.Name.Contains("lblGoodsName"))
                            {
                                m_dictGoodsName.Add(ctrl.Name.Replace("pnl", ""), (LabelX)ctrl1);
                                continue;
                            }
                            if (ctrl1.Name.Contains("GoodsSpec"))
                            {
                                m_dictGoodsSpec.Add(ctrl.Name.Replace("pnl", ""), (LabelX)ctrl1);
                                continue;
                            }
                            if (ctrl1.Name.Contains("txtAmount"))
                            {
                                m_dictAmount.Add(ctrl.Name.Replace("pnl", ""), (TextBox)ctrl1);
                                continue;
                            }
                            if (ctrl1.Name.Contains("txtCollectAmount"))
                            {
                                m_dictCollectAmount.Add(ctrl.Name.Replace("pnl", ""), (TextBox)ctrl1);
                                continue;
                            }
                            if (ctrl1.Name.Contains("txtCollectStatus"))
                            {
                                m_dictCollectStatus.Add(ctrl.Name.Replace("pnl", ""), (TextBox)ctrl1);
                                continue;
                            }
                            if (ctrl1.Name.Contains("txtCollectCount"))
                            {
                                m_dictCollectCount.Add(ctrl.Name.Replace("pnl", ""), (TextBox)ctrl1);
                                continue;
                            }
                        }
                        catch { 
                        }
                    }
                }
            }
            // 动画
            AppInfo.AnimateWindow(this.Handle, 100, AppInfo.AW_CENTER | AppInfo.AW_ACTIVE | AppInfo.AW_VER_NEGATIVE);
            this.Refresh();
            timerShowData.Enabled = true;
        }

        private void timerShowData_Tick(object sender, EventArgs e)
        {
            timerShowData.Enabled = false;
            m_strBillCode = m_dictInfo["BillCode"].ToString();
            if (!m_strBillCode.Equals(""))
            {
                _showBillInfo(m_strBillCode);
                _getBillList();
                pnlNext.Visible = false;
                txtSupervisionCode.Text = "";
                txtSupervisionCode.Focus();
            }
            else {
                pnlNext.Visible = true;
            }
        }

        private void btnReturn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (txtSupervisionCode.Text.Trim().Length != 20) {
                    CommFun._messageBoxShow("电监编码长度不合法,应为20位！");
                    return;
                }
                m_strSupervisionCode = txtSupervisionCode.Text.Trim();
                _dealCode();                
                txtSupervisionCode.Text = "";
                // 下一单
                if (lblBillCheckStatus.Text.Equals("全采")) {
                    btnNext_Click(null,null);
                }
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (!txtGoodsCount0.Text.Equals("0"))
            {
                if (CommFun._messageBoxShow("当前单据未采码完成，是否确定要采集其他单据？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK)
                {
                    return;
                }
            }
            pnlNext.Visible = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            pnlNext.Visible = false;
        }

        private void pnlNext_VisibleChanged(object sender, EventArgs e)
        {
            if (pnlNext.Visible)
            {
                txtBillCode.Text = "";
                txtBillCode.Focus();
            }
            else
            {
                txtSupervisionCode.Text = "";
                txtSupervisionCode.Focus();
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            // 取单据编号
            string strCode = txtBillCode.Text.Trim();
            if (strCode.Length < 2)
            {
                CommFun._messageBoxShow("编码位数太短,请确认！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                _showBillInfo(strCode);
                // 显示单据汇总信息
                if (!pnlNext.Visible) {
                    timerShowData.Enabled = true;
                }                
            }
        }

        /// <summary>
        /// 显示单据信息
        /// </summary>
        /// <param name="strBillCode"></param>
        private void _showBillInfo(string strCode)
        {
            try
            {
                string strSql = "";
                strSql = string.Format("select PrescriptionCode,PatientIdCode,PatientName,Code,PickerName,SupervisionCodeCollectStatus from TH_PharmacyStockOut where Code = '{0}'", strCode);
                DataTable dt = AppInfo._openSql_DataTable(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["SupervisionCodeCollectStatus"].ToString().Equals("全采"))
                    {
                        CommFun._messageBoxShow("该单据已采集完成，请换新单据！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        m_dictInfo["BillCode"] = dt.Rows[0]["Code"].ToString();
                        m_strBillCode = m_dictInfo["BillCode"];
                        txtSupplierCode.Text = dt.Rows[0]["PrescriptionCode"].ToString();
                        txtSupplierName.Text = dt.Rows[0]["PatientName"].ToString();
                        gbMain.Text = string.Format("单据信息(编号:{0})", m_strBillCode);
                        pnlNext.Visible = false;                        
                    }
                }
                else
                {
                    CommFun._messageBoxShow("该单号不存在,请确认！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch
            {
            }            
        }

        private void txtBillCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnOK_Click(null,null);
            }
        }
        #endregion

        private void btnScanBat_Click(object sender, EventArgs e)
        {
            this.Hide();
            this.Close();
            frmCollectPharmacyStockOut_Bat frm = new frmCollectPharmacyStockOut_Bat();
            if (frm.m_dictInfo.ContainsKey("BillCode"))
            {
                frm.m_dictInfo["BillCode"] = m_strBillCode;
            }
            else
            {
                frm.m_dictInfo.Add("BillCode", m_strBillCode);
            }            
            frm.ShowDialog();
        }
    }
}
